<?php

namespace App\Models;

class Task extends Base
{
    // 转换数组为字符串
    public function setParamsAttribute($value){
        if (is_array($value) && $value){
            $this->attributes['params'] = json_encode($value, JSON_UNESCAPED_UNICODE);
        } else {
            $this->attributes['params'] = null;
        }
    }

    // 转换字符串为数组
    public function getParamsAttribute($value){
        return $value ? json_decode($value, true) : [];
    }
    
    /**
     * 文案（一对一关系）
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function papper() {
        return $this->belongsTo(Papper::class);
    }
    
    /**
     * 用户（一对一关系）
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user() {
        return $this->belongsTo(User::class);
    }
    
    /**
     * 用户（一对一关系）
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function creator() {
        return $this->belongsTo(User::class, 'creator_id', 'id');
    }
    
    /**
     * 课程文件（一对多关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function files() {
        return $this->hasMany(TaskFile::class, 'papper_id', 'papper_id');
    }

    /**
     * 课程封面（一对一关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function video() {
        return $this->hasOne(TaskFile::class, 'papper_id', 'papper_id')
            ->where('type', 2);
    }

    /**
     * 视频（一对一关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function videos() {
        return $this->hasMany(TaskFile::class, 'papper_id', 'papper_id')
            ->where('type', 2);
    }

    public function publish() {
        return $this->hasMany(TaskPublish::class);
    }
}
